//
//  WYAddProductController.m
//  Boss
//
//  Created by admin on 2018/7/5.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYAddProductController.h"
#import "WYUploadModel.h"
#import "WYEditHomePageController.h"
#import "UIImage+WYSaveImage.h"
@interface WYAddProductController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *topHeight;
@property (strong, nonatomic) IBOutlet UIImageView *productImageView;
@property (strong, nonatomic) IBOutlet UITextField *titleTextField;
//@property (strong, nonatomic) IBOutlet UITextField *introductionTextField;
@property (strong, nonatomic) IBOutlet UITextView *introductionTextField;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *textfieldHeight;

@property (nonatomic,strong)NSString *pathString;

@property (nonatomic,strong)WYUploadModel *model;

@end

@implementation WYAddProductController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    // Do any additional setup after loading the view from its nib.
}
-(void)setupUI
{
    [self setupTextView];
    self.topHeight.constant = self.navHeight;
    self.navigationItem.title = @"添加产品服务";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:(UIBarButtonItemStyleDone) target:self action:@selector(clickCancelAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:(UIBarButtonItemStyleDone) target:self action:@selector(clickSaveAction)];
    self.productImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImageViewAction:)];
    [self.productImageView addGestureRecognizer:ges];
    
    [self.productImageView setContentMode:(UIViewContentModeScaleAspectFill)];
    self.productImageView.clipsToBounds = YES;
    
    if (self.isEdit) {
        
        self.productImageView.image  = self.image;
        self.titleTextField.text = self.service.title;
        self.introductionTextField.text = self.service.content;
        
    }
    
    [self setInfo];
}
-(void)setInfo
{
    self.introductionTextField.scrollEnabled = NO;
    self.introductionTextField.scrollsToTop = NO;
    self.introductionTextField.showsHorizontalScrollIndicator = NO;
    self.introductionTextField.enablesReturnKeyAutomatically = YES;
    self.introductionTextField.delegate = self;
}
-(void)textViewDidChange:(UITextView *)textView
{
    NSInteger height = ceilf([self.introductionTextField sizeThatFits:CGSizeMake(self.introductionTextField.bounds.size.width, MAXFLOAT)].height);
    
    if (self.textfieldHeight.constant <= height) { // 高度不一样，就改变了高度
        //_textH = height;
        self.textfieldHeight.constant = height;
        
    }
}
- (void)setupTextView
{
    
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"产品介绍,服务内容";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [self.introductionTextField addSubview:placeHolderLabel];
    placeHolderLabel.font = [UIFont systemFontOfSize:13.f];
    [self.introductionTextField setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}
-(void)clickImageViewAction:(UITapGestureRecognizer *)ges
{
    
    
    WEAKSELF
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
   
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
         imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (@available(iOS 11, *)) {
            UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
            
        }
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    if (IS_IPAD) {
        UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
        popPresenter.sourceView = ges.view;
        popPresenter.sourceRect = ges.view.bounds;
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    
    
}



-(void)clickCancelAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)clickSaveAction
{
    
    if (!self.titleTextField.text.length) {
        [self toast:@"请输入标题"];return;
    }
    if (!self.introductionTextField.text.length) {
        [self toast:@"请输入简介"];return;
    }
    if (self.isEdit) {
        
    }else{
        if (!self.model.visitUrl.length) {
            [self toast:@"请添加封面图"];return;
        }
    }
    
    
    
    WEAKSELF
    if (self.isEdit) {
        [WYHttpServer editProductServiceWithID:self.service.id WithPicUrl:self.service.picUrl WithTitle:self.titleTextField.text WithContent:self.introductionTextField.text SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
            if (success) {
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[WYEditHomePageController class]]) {
                        WYEditHomePageController *A =(WYEditHomePageController *)controller;
                        [weakSelf.navigationController popToViewController:A animated:YES];
                    }
                }
             //   [weakSelf toast:@"修改成功"];
                
            }else{
                [weakSelf toast:errorMessage];
            }
            
            
            
            
        }];
        
        
        
        
    }else{
        
        
        [WYHttpServer addProductSerViceWithPicUrl:self.model.visitUrl WithTitle:self.titleTextField.text WithContent:self.introductionTextField.text SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
            
            if (success) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"refreshProductService" object:nil];
                
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            
            
            
        }];
        
        
    }
    
   
    
    
    
    
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData * imageDate = UIImageJPEGRepresentation(photo, 0.1);
    UIImage *image = [UIImage imageWithData:imageDate];
    
    NSString *path = [image QCloudTempFilePathWithExtension:@"PNG"];
    self.pathString = path;
    [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
    
    
    
 //   [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   // [self showLoading:@""];
    self.productImageView.image = photo;
    WEAKSELF
    [WYHttpServer uploadImageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        WYUploadModel *model = [WYUploadModel getupLoadModelFromJson:response[@"result"]];
        [weakSelf upLoadWithPath:model.uploadUrl];
        weakSelf.model = model;
        
        
    }];
    
    
    
    
    
    
}
-(void)upLoadWithPath:(NSString *)path
{
    WEAKSELF
    [WYHttpServer PUTWithURLStr:path filePath:self.pathString SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            weakSelf.service.picUrl = weakSelf.model.visitUrl;
          //  [MBProgressHUD hideHUDForView:self.view animated:YES];
           // [self hideLoading];
//            [weakSelf editHeaderImageview];
        }else{
            
        }
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
